<template>
    <div class="container">
        <!-- 商品主要信息 -->
        <Card class="goods" style="width:890px">
            <!-- 商品名称 -->
            <Input class="goods_name" v-model="goods_name" placeholder="商品名称" clearable></Input>
            <!-- 商品详情，富文本编辑器 -->
            <div class="goods_content" ref="editor" style="text-align:left"></div>
        </Card>
        <!-- 商品的其他信息 -->
        <Card class="info" style="width:300px">
            <p slot="title">
                <Icon type="ios-paperplane-outline"></Icon>
                商品信息
            </p>

            <span class="belone_menu_uid label">目录：</span>
            <Cascader :data="menuData" v-model="menu"></Cascader>

            <span class="goods_describe label">简介：</span>
            <Input class="goods_describe_input input" v-model="goods_describe" type="textarea" :autosize="{minRows: 3}" placeholder="商品简介,如果未填写则抓取正文前50个文字"
                clearable></Input>

            <span class="goods_price label">商品价格：</span>
            <Input class="goods_price_input input" v-model="goods_price" placeholder="商品价格" type="number" number="true"></Input>

            <span class="goods_status label">是否上架：</span>
            <Switch class="goods_status_input" v-model="goods_status" @on-change="goods_status=goods_status?1:0"></Switch>

            <span class="news_file1 label">商品封面：</span>
            <!-- 商品封面 -->
            <Upload class="news_file1_input input" type="drag" name="goods" action="$api/api/upload/goods" :on-success="uploadSuccess"
                :on-error="uploadError">
                <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击或拖拽图片到此上传</p>
                </div>
            </Upload>
            <!-- 
                商品相册，这个可以上传多个图片，
                引用iview 的上传，文档地址：https://www.iviewui.com/components/upload
             -->
            <span class="goods_file_arr label">商品相册</span>
            <div class="goods_file_arr input">
                <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                    <template v-if="item.status === 'finished'">
                        <img :src="'$api'+item.url">
                        <div class="demo-upload-list-cover">
                            <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                        </div>
                    </template>
                    <template v-else>
                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                </div>
                <Upload ref="upload" name="goods" :show-upload-list="false" :default-file-list="defaultList" :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize"
                    :before-upload="handleBeforeUpload" multiple type="drag" action="$api/api/upload/goods"
                    style="display: inline-block;width:58px;">
                    <div style="width: 58px;height:58px;line-height: 58px;">
                        <Icon type="camera" size="20"></Icon>
                    </div>
                </Upload>
                <Modal title="查看图片" v-model="visible">
                    <img :src="'$api' + imgUrl" v-if="visible" style="width: 100%">
                </Modal>
            </div>
        </Card>

        <Button class="submit" type="primary" @click="submit">发布</Button>
    </div>
</template>
<script>
    import E from 'wangeditor'
    export default {
        data() {
            return {
                editor: '', //富文本编辑器变量
                menuData: [], //所有目录
                menu: [], //商品所在目录，数据库只存UID，需要反向找出

                belone_menu_uid: '', //商品所在目录的UID
                belone_top_menu_uid: '', //商品所在目录的最顶级UID
                goods_name: '', //商品名字
                goods_content: '', //上哦详情
                goods_file1: '', //商品封面图
                uid: 0, //商品的Uid，如果是0则表示是新增，不为0则表示是修改
                goods_price: '', //商品价格
                goods_describe: '', //商品描述，如果不填则截取详情前50个文字
                goods_status: 0, //商品状态，上架/下架

                defaultList: [], //iview上传插件的变量
                imgUrl: '', //iview上传插件的变量
                visible: false, //iview上传插件的变量
                uploadList: [] //iview上传插件的变量
            }
        },
        methods: {
            /**
             *@function 上传成功触发的回调行数
             *@param {Object} response 上传成功返回的服务器回调数据
             *@param {Object} file 当文件为一个的时候存在，为文件信息
             *@param {Object} file 当文件为多个的时候存在，为文件信息数组
             *@description 使用iview 的上传文件，参考文档https://www.iviewui.com/components/upload
             */
            uploadSuccess: function (response, file, fileList) {

                if (response.state == '1') {
                    this.$Message.success('上传成功');
                    this.goods_file1 = response.file.store_result
                } else {
                    this.$Message.error('上传失败');
                }
            },
            /**
             *@function 上传失败触发的回调函数
             *@description 使用iview 的上传文件，参考文档https://www.iviewui.com/components/upload
             */
            uploadError: function (error, file, fileList) {
                this.$Message.error('上传失败');
            },
            /**
            @function 相册上传的事件，参考https://www.iviewui.com/components/upload
            @param {String} url 上传成功后的图片URL
            */
            handleView(url) {
                this.imgUrl = url;
                this.visible = true;
            },
            /**
             * @function 图片删除
             * @param {Obeject} 图片信息，通过判断图片信息所在的位置删除
             */
            handleRemove(file) {
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            },
            /**
             * @function 上传成功
             * @param {Object} res 上传成功返回的服务器回调数据
             * @param {Object} file 当文件为一个的时候存在，为文件信息
             */
            handleSuccess(res, file) {
                this.$Notice.success({
                    title: '上传成功',
                    desc: ''
                });
                file.url = res.file.store_result;
            },

            /**
             * @function 上传失败
             * @param {Object} file 当文件为一个的时候存在，为文件信息
             */
            handleFormatError(file) {
                this.$Notice.warning({
                    title: '上传失败',
                    desc: '图片不支持的图片格式.'
                });
            },
            /**
             * @function 上传失败
             * @param {Object} file 当文件为一个的时候存在，为文件信息
             */
            handleMaxSize(file) {
                this.$Notice.warning({
                    title: '上传失败',
                    desc: '图片过大，请上传小于2M的图片.'
                });
            },
            /**
             * @function 上传前检查数量
             */
            handleBeforeUpload() {
                const check = this.uploadList.length < 5;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多支持五张图片'
                    });
                }
                return check;
            },
            /**
            @function 上传更新 
            */
            submit: function () {
                //处理goods_file_arr,转成只有url的数组，再转成字符串
                let arr = []
                this.uploadList.forEach((element) => {
                    arr.push(element.url)
                })
                this.goods_describe = this.goods_describe == '' ? this.editor.txt.text().substr(0, 50) : this.goods_describe

                let that = this
                this.$axios.post(this.$api+'/api/admin/goodsUpdate', {
                        'uid': that.uid,
                        'belone_menu_uid': that.belone_menu_uid,
                        'belone_top_menu_uid': that.belone_top_menu_uid,
                        'goods_name': that.goods_name,
                        'goods_content': that.goods_content,
                        'goods_file1': that.goods_file1,
                        'goods_price': that.goods_price,
                        'goods_describe': that.goods_describe,
                        'goods_status': that.goods_status,
                        'goods_file_arr': arr.join('||')
                    }, {
                        headers: {
                            'Access-Control-Request-Method': 'Origin'
                        },
                        withCredentials: true
                    })
                    .then(function (response) {

                        if (response.data.state > 0) {
                            that.$Notice.success({
                                title: '发布成功',
                                desc: true ? '' : 'Here is the notification description. Here is the notification description. '
                            });
                        } else {
                            that.$Notice.error({
                                title: '发布失败',
                                desc: true ? '' : 'Here is the notification description. Here is the notification description. '
                            });
                        }
                    })
                    .catch(function (response) {

                        that.$Notice.error({
                            title: '发布失败',
                            desc: true ? '' : 'Here is the notification description. Here is the notification description. '
                        });
                    })
            }
        },
        watch: {
            menu: function () {
                /* 当商品所在目录发生改变的时候，商品所属的目录UID 也要跟着改变 */
                this.belone_menu_uid = this.menu[this.menu.length - 1]
                this.belone_top_menu_uid = this.menu[0]
            },
            goods_describe: function () {
                /* 商品简介描述，控制在50个字 */
                if (this.goods_describe.length > 50) {
                    this.goods_describe = this.goods_describe.substr(0, 50)
                }
            }
        },
        mounted() {
            /* 设置富文本编辑器，使用 wangEditor,使用说明查阅：https://www.kancloud.cn/wangfupeng/wangeditor3/335774*/
            this.editor = new E(this.$refs.editor)
            //配置文章内容存储变量
            this.editor.customConfig.onchange = (html) => {
                this.goods_content = html
            }
            //配置图片上传服务器
            this.editor.customConfig.uploadImgServer = this.$api+'/api/upload/editor' //上传地址
            this.editor.customConfig.uploadFileName = 'editor' //上传name
            this.editor.customConfig.uploadImgMaxLength = 1 //上传的最大数量
            //创建富文本编辑器
            this.editor.create()
            this.uploadList = this.$refs.upload.fileList;
        },
        created: function () {
            let that = this
            this.$axios.get(this.$api+'/api/admin/MenuGet', {
                    headers: {
                        'Access-Control-Request-Method': 'Origin'
                    },
                    withCredentials: true
                })
                .then(function (response) {
                    that.menuData = response.data.menu
                })
            if (this.$route.query.uid) {
                this.$axios.get(this.$api+'/api/product?uid=' + that.$route.query.uid, {
                        headers: {
                            'Access-Control-Request-Method': 'Origin'
                        },
                        withCredentials: true
                    })
                    .then(function (response) {

                        that.goods_name = response.data.detail.detail.goods_name
                        that.goods_content = response.data.detail.detail.goods_content
                        that.editor.txt.html(that.goods_content)
                        that.goods_file1 = response.data.detail.detail.goods_file1
                        that.uid = response.data.detail.detail.uid
                        that.goods_price = response.data.detail.detail.goods_price
                        that.goods_describe = response.data.detail.detail.goods_describe
                        that.goods_status = response.data.detail.detail.goods_status == 1

                        let file_arr = response.data.detail.detail.goods_file_arr.split("||")

                        file_arr.forEach(element => {

                            that.uploadList.push({
                                url: element,
                                status: 'finished'
                            })
                        })

                        let menu = response.data.detail.breadcrumb.reverse()
                        menu.forEach(element => {
                            that.menu.push(element.uid)
                        })
                    })
                    .catch(function (response) {

                    })
            }
        }
    }
</script>

<style lang="less" scoped>
    .container {
        width: 1200px;
        margin: 20px auto;
        .goods {
            float: left;
            height: 100%;
            margin-right: 10px;
            .goods_content {
                margin: 20px auto;
            }
        }
        .info {
            float: left;
            .label {
                height: 32px;
                line-height: 32px;
                width: 30%;
                display: inline-block;
            }
            .input {
                width: 100%;
                display: inline-block;

            }
            .goods_status_input {
                margin-right: 100px;
            }
            .goods_file_arr {
                .demo-upload-list {
                    display: inline-block;
                    width: 60px;
                    height: 60px;
                    text-align: center;
                    line-height: 60px;
                    border: 1px solid transparent;
                    border-radius: 4px;
                    overflow: hidden;
                    background: #fff;
                    position: relative;
                    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
                    margin-right: 4px;
                }
                .demo-upload-list img {
                    width: 100%;
                    height: 100%;
                }
                .demo-upload-list-cover {
                    display: none;
                    position: absolute;
                    top: 0;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background: rgba(0, 0, 0, .6);
                }
                .demo-upload-list:hover .demo-upload-list-cover {
                    display: block;
                }
                .demo-upload-list-cover i {
                    color: #fff;
                    font-size: 20px;
                    cursor: pointer;
                    margin: 0 2px;
                }
            }
        }
        .submit {
            float: left;
            margin: 0 500px;
            width: 200px;
            display: block;
        }
    }
</style>